package com.yq588.forward.controller;

import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.yq588.forward.utils.StreamUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpCookie;
import java.util.*;

@Controller
public class IndexController {
    @Autowired
    private Environment env; //不需要getter setter方法

    @RequestMapping("/wel")
    public ModelAndView wel(HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView("index");
        return modelAndView;

    }

    @RequestMapping("/forwardhandout/dispatch")
    @ResponseBody
    public void index(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        HashMap<String, Object> paramMap = new HashMap<>();
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (String key : parameterMap.keySet()) {
            String[] value = parameterMap.get(key);
            paramMap.put(key, value[0]);
        }
        String body = ServletUtil.getBody(request);
        Map<String, Object> map = (Map<String, Object>) JSON.parse(body);

        String apiurl = request.getParameter("apiurl");
        if (apiurl == null) {
            if (map != null) {
                apiurl = map.get("apiurl").toString();
                for (String key : map.keySet()) {
                    //String[] value = (String[]) map.get(key).toString();
                    paramMap.put(key, map.get(key).toString());
                }
            }
        }
        System.out.println("-----------------------------------------apiurl = " + apiurl);
        System.out.println("-----------------------------------------body = " + body);
        System.out.println("-----------------------------------------paramMap = " + JSON.toJSONString(paramMap));
        System.out.println("-----------------------------------------Method = " + request.getMethod());
        System.out.println("-----------------------------------------参数 = " + HttpUtil.toParams(paramMap));
        System.out.println("-----------------------------------------Headers = " + JSON.toJSONString(ServletUtil.getHeaderMap(request)));
        System.out.println("-----------------------------------------CookiesRequest = " + JSON.toJSONString(request.getCookies()));
        System.out.println("-----------------------------------------CookiesHutool = " + JSON.toJSONString(ServletUtil.readCookieMap(request)));
        String method = request.getMethod();
        HttpRequest httpRequest = null;
        if ("POST".equals(method)) {
            String tempParams = HttpUtil.toParams(paramMap);
            httpRequest = HttpRequest.post(apiurl + "?" + tempParams);
            String bodyjson = JSONUtil.toJsonStr(paramMap);
            httpRequest.body(bodyjson);//表单内容
            httpRequest.form(paramMap);//表单内容
        }
        if ("GET".equals(method)) {
            String tempParams = HttpUtil.toParams(paramMap);
            httpRequest = HttpRequest.get(apiurl + "?" + tempParams);
        }
        //HttpRequest httpRequest = HttpRequest.post(env.getProperty("app_url"));
        Map<String, String> headerMap = ServletUtil.getHeaderMap(request);
        for (String key : headerMap.keySet()) {
            String value = headerMap.get(key);
            httpRequest.header(key, value);//头信息，多个头信息多次调用此方法即可
        }

        Map<String, Cookie> stringCookieMap = ServletUtil.readCookieMap(request);

        if (stringCookieMap != null) {
            for (String key : stringCookieMap.keySet()) {
                Cookie cookie = stringCookieMap.get(key);
                httpRequest.cookie(String.valueOf(cookie));
            }
        }

        httpRequest.timeout(20000);//超时，毫秒
        httpRequest.setEncodeUrlParams(true);
        HttpResponse execute = httpRequest.execute();
        String body1 = execute.body();
        List<HttpCookie> HttpResponsecookies = execute.getCookies();
        Map<String, List<String>> HttpResponseheaders = execute.headers();

        System.out.println("-----------------------------------------HttpResponse-Headers = " + JSON.toJSONString(HttpResponseheaders));
        System.out.println("-----------------------------------------HttpResponse-cookies = " + JSON.toJSONString(HttpResponsecookies));

        InputStream ins = execute.bodyStream();
        //System.out.println(body1);
        //modelAndView.addObject("page", body);
        //return modelAndView;
        ServletUtil.write(response, ins, HttpResponseheaders.get("Content-Type").get(0));
    }

    @RequestMapping("/fasong")
    @ResponseBody
    public ModelAndView fasong(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());

        List<Map<String, Object>> list = new ArrayList<>();

        Map<String, Object> map = new HashMap<>();
        map.put("id", 1);
        map.put("name", "sdgsd");
        list.add(map);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("id", 2);
        map2.put("name", "绿色肯德基");
        list.add(map2);

        Map<String, Object> mapjson = new HashMap<>();
        mapjson.put("data", JSON.toJSONString(list));
        mapjson.put("code", 123);
        mapjson.put("msg", "sdtsd是大法官");

        String json = JSON.toJSONString(mapjson);
        String res = HttpUtil.post("http://127.0.0.1:8082/shou", mapjson);
        modelAndView.addObject("data", res);
        return modelAndView;
    }

    @RequestMapping("/shou")
    @ResponseBody
    public ModelAndView shou(HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, Object> map) {
        ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
        String data = map.get("data").toString();
        //Map maps = (Map)JSON.parse(data);
        List<Map<String, Object>> list = (List<Map<String, Object>>) JSONArray.parse(data);
        System.out.println("maps = " + list);
        return modelAndView;
    }
}
